//
//  SABuyMessageVC.m
//  saasRetail
//
//  Created by mac on 2023/5/29.
//

#import "SABuyMessageVC.h"
#import "UILabel+NSMutableAttributedString.h"
#import "ZXingObjC.h"
#import "QRCodePermissions.h"
#import "SASmsBalanceAPI.h"
#import "SABuyMessageCell.h"
#import "SASmsPackageListModel.h"
#import "SASmsPackageListAPI.h"
#import "SASmsRechargeAPI.h"
#import "LBXScanWrapper.h"
#import "SASmsQueryStatusAPI.h"
#import "SASmsAppCreateOrderAPI.h"
#import "SACreateOrderModel.h"
#import <WechatOpenSDK/WXApi.h>

@interface SABuyMessageVC ()<UITableViewDelegate, UITableViewDataSource, HTTPAPIDelegate>

@property (nonatomic, strong) UILabel *messageLab;
@property (nonatomic, strong) UILabel *numLab;
@property (nonatomic, strong) UIImageView *codeImageV;
@property (nonatomic, strong) UILabel *codeLab;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) SASmsBalanceAPI *smsBalanceAPI;
@property (nonatomic, strong) SASmsPackageListAPI *smsPackageListAPI;
@property (nonatomic, strong) NSMutableArray<SASmsPackageListModel *> *dataMarr;
@property (nonatomic, strong) SASmsRechargeAPI *smsRechargeAPI;

@property (nonatomic, strong) NSString *jspayUrl;//二维码图片
@property (nonatomic, strong) NSString *rechargeNo;//充值订单号
@property (nonatomic, strong) SASmsQueryStatusAPI *smsQueryStatusAPI;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UIButton *payBtn;
@property (nonatomic, strong) SASmsAppCreateOrderAPI *smsAppCreateOrderAPI;
@property (nonatomic, strong) SACreateOrderModel *orderModel;

@end

@implementation SABuyMessageVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.smsBalanceAPI == api) {
        NSString *num = [NSString stringWithFormat:@"%@",data[@"data"][@"smsBalance"]];
        self.numLab.text = [NSString stringWithFormat:@"剩余%@条",num];
        [self.numLab setAttributedStringWithSubString:num color:[UIColor redColor] font:kBFont(20)];
    }else if (self.smsPackageListAPI == api) {
        self.dataMarr = [SASmsPackageListModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        [self.tableView reloadData];
    }else if (self.smsRechargeAPI == api) {
        self.jspayUrl = [NSString stringWithFormat:@"%@",data[@"data"][@"jspayUrl"]];
        self.rechargeNo = [NSString stringWithFormat:@"%@",data[@"data"][@"rechargeNo"]];
        self.codeLab.hidden = NO;
        self.codeImageV.hidden = NO;
        self.payBtn.hidden = NO;
        self.codeImageV.image = [LBXScanWrapper createQRWithString:self.jspayUrl size:self.codeImageV.bounds.size];
        
        [self.timer invalidate];
        self.timer = nil;;
        self.timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
    }else if (self.smsQueryStatusAPI == api) {
        NSString *status = [NSString stringWithFormat:@"%@",data[@"data"][@"status"]];
        if ([status isEqualToString:@"2"]) {
            [self.timer invalidate];
            self.timer = nil;;
            [self.smsBalanceAPI sendRequestToServerWithType:GET];
//            [self.smsRechargeAPI sendRequestToServerWithActivityViewAndMask:POST];
        }
    }else if (self.smsAppCreateOrderAPI == api) {
        self.orderModel = [SACreateOrderModel mj_objectWithKeyValues:data[@"data"]];
        self.rechargeNo = self.orderModel.rechargeNo;
        [self.timer invalidate];
        self.timer = nil;;
        self.timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
        [self wxPayOrder];
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
   
}

#pragma mark - UITableView Delegate & DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataMarr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SABuyMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SABuyMessageCell" forIndexPath:indexPath];
    cell.model = self.dataMarr[indexPath.section];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 
    for (SASmsPackageListModel *model in self.dataMarr) {
        model.isSelect = NO;
    }
    self.dataMarr[indexPath.section].isSelect = YES;
    [tableView reloadData];
    NSString *amount = [NSString stringWithFormat:@"%0.2lf",self.dataMarr[indexPath.section].amount/100].getEffectivePointString;
    self.codeLab.text = [NSString stringWithFormat:@"扫码支付金额：%@元",amount];
    [self.codeLab setAttributedStringWithSubString:@"扫码支付金额：" color:kBlackColor font:kFont(15)];
    self.codeLab.hidden = NO;
    self.payBtn.hidden = NO;
//    self.smsRechargeAPI.packageType = self.dataMarr[indexPath.section].id;
//    [self.smsRechargeAPI sendRequestToServerWithActivityViewAndMask:POST];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(80);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kScaleNum(0.01);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

#pragma mark - event
- (void)timerFired {
    self.smsQueryStatusAPI.rechargeNo = self.rechargeNo;
    [self.smsQueryStatusAPI sendRequestToServerWithType:GET];
}

-(void)backToLastVC {
    [self.timer invalidate];
    self.timer = nil;;
    [self.navigationController popViewControllerAnimated:YES];
}

//立即支付
-(void)clickedPayBtn {
//    [self loadImageFinished:self.codeImageV.image];
    
    SASmsPackageListModel *selectModel = nil;
    for (SASmsPackageListModel *model in self.dataMarr) {
        if (model.isSelect == YES) {
            selectModel = model;
        }
    }
    if (selectModel == nil) {
        [Prompt popPromptViewWithMsg:@"请先选择短信套餐" duration:2];
    }else {
        self.smsAppCreateOrderAPI.packageid = selectModel.id;
        [self.smsAppCreateOrderAPI sendRequestToServerWithType:POST];
    }
}

//微信支付订单
-(void)wxPayOrder {
    
    PayReq *rep = [[PayReq alloc] init];
    if ([WXApi isWXAppInstalled]) {
        rep.openID = self.orderModel.appid;
        rep.partnerId = self.orderModel.partnerId;
        rep.prepayId = self.orderModel.prepayId;
        rep.package = self.orderModel.packageValue;
        rep.nonceStr = self.orderModel.noncestr;
        rep.timeStamp = [self.orderModel.timestamp intValue];
        rep.sign = self.orderModel.sign;
        [WXApi sendReq:rep completion:^(BOOL success) {
            
        }];
    }else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [Prompt popPromptViewWithMsg:@"请安装微信客户端" duration:2];
        });
    }
}

- (void)loadImageFinished:(UIImage *)image
{
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
}
 
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error == nil) {
        NSURL * url = [NSURL URLWithString:@"weixin://scanQRCode"];
        [[UIApplication sharedApplication] openURL:url options:[NSDictionary dictionary] completionHandler:^(BOOL success) {
            
        }];
    }else {
        [Prompt popPromptViewWithMsg:@"图片保存失败" duration:3];
    }
}

#pragma mark - initUI
-(void)initUI {
    
    [self setNavigationItemBackBBIAndTitle:@"短信购买"];
    [self setBgImage:nil];
    self.view.backgroundColor = kBgColor;
    
    [self.view addSubview:self.messageLab];
    [self.view addSubview:self.numLab];
    [self.view addSubview:self.codeImageV];
    [self.view addSubview:self.codeLab];
    [self.view addSubview:self.payBtn];
    [self.view addSubview:self.tableView];
    
    
    self.codeLab.hidden = YES;
    self.codeImageV.hidden = YES;
    self.payBtn.hidden = YES;
    
    [self.smsBalanceAPI sendRequestToServerWithType:GET];
    [self.smsPackageListAPI sendRequestToServerWithType:GET];
}

-(UILabel *)messageLab {
    if (!_messageLab) {
        _messageLab = [[UILabel alloc] initWithFrame:SARectMake(10, StatusHeight + 15, 100, 25)];
        _messageLab.text = @"可用短信:";
        _messageLab.font = kFont(15);
        _messageLab.textColor = kBlackColor;
    }
    return _messageLab;
}

-(UILabel *)numLab {
    if (!_numLab) {
        _numLab = [[UILabel alloc] initWithFrame:SARectMake(80, StatusHeight + 15, 200, 25)];
        _numLab.text = @"剩余100条";
        _numLab.font = kBFont(15);
        _numLab.textColor = kBlackColor;
    }
    return _numLab;
}

-(UIImageView *)codeImageV {
    if (!_codeImageV) {
        _codeImageV = [[UIImageView alloc] initWithFrame:CGRectMake(kScaleNum(120), kScreenHeight - kScaleNum(230), kScaleNum(135), kScaleNum(135))];
    }
    return _codeImageV;
}

-(UILabel *)codeLab {
    if (!_codeLab) {
        _codeLab = [[UILabel alloc] initWithFrame:CGRectMake(0, kScreenHeight - kScaleNum(104), kScreenWidth, kScaleNum(20))];
        _codeLab.text = @"";
        _codeLab.font = kFont(15);
        _codeLab.textAlignment = NSTextAlignmentCenter;
        _codeLab.textColor = [UIColor redColor];
    }
    return _codeLab;
}

-(UIButton *)payBtn {
    if (!_payBtn) {
        _payBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _payBtn.frame = CGRectMake(kScaleNum(125), kScreenHeight - kScaleNum(74), kScaleNum(125), kScaleNum(40));
        [_payBtn setTitle:@"支付" forState:UIControlStateNormal];
        [_payBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _payBtn.titleLabel.font = kFont(18);
        _payBtn.backgroundColor = [UIColor redColor];
        _payBtn.layer.cornerRadius = 5;
        _payBtn.layer.masksToBounds = YES;
        [_payBtn addTarget:self action:@selector(clickedPayBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _payBtn;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight + 55), kScreenWidth, kScreenHeight - kScaleNum(110 + StatusHeight + 60)) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = kBgColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[SABuyMessageCell class] forCellReuseIdentifier:@"SABuyMessageCell"];
    }
    return _tableView;
}

-(SASmsBalanceAPI *)smsBalanceAPI {
    if (!_smsBalanceAPI) {
        _smsBalanceAPI = [SASmsBalanceAPI apiWithDelegate:self];
    }
    return _smsBalanceAPI;
}

-(SASmsPackageListAPI *)smsPackageListAPI {
    if (!_smsPackageListAPI) {
        _smsPackageListAPI = [SASmsPackageListAPI apiWithDelegate:self];
    }
    return _smsPackageListAPI;
}

-(NSMutableArray<SASmsPackageListModel *> *)dataMarr {
    if (!_dataMarr) {
        _dataMarr = [NSMutableArray array];
    }
    return _dataMarr;
}

-(SASmsRechargeAPI *)smsRechargeAPI {
    if (!_smsRechargeAPI) {
        _smsRechargeAPI = [SASmsRechargeAPI apiWithDelegate:self];
    }
    return _smsRechargeAPI;
}

-(SASmsQueryStatusAPI *)smsQueryStatusAPI {
    if (!_smsQueryStatusAPI) {
        _smsQueryStatusAPI = [SASmsQueryStatusAPI apiWithDelegate:self];
    }
    return _smsQueryStatusAPI;
}

-(SASmsAppCreateOrderAPI *)smsAppCreateOrderAPI {
    if (!_smsAppCreateOrderAPI) {
        _smsAppCreateOrderAPI = [SASmsAppCreateOrderAPI apiWithDelegate:self];
    }
    return _smsAppCreateOrderAPI;
}

@end
